#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include "fetcher.h"
#include "utils.h"

#define DEBUG 0

int gen_rsurl(const char * keyword, char * rsurl);
void tidy_str(char * src, char * res);

int main(int argc, char * argv[])
{
	char keyword[101], *desfile;
	FILE *desfp;
	FETCHER *fetcher;
	char *htmlsrc;
	char rsurl[1024];
	char dlurl[1024];
	char mp3url[1024];
	char decode_F[20];
	char decode_I[1024];
	char song[256];
	char singer[256];
	char album[256];
	char mp3size[20];
	char song_t[256];
	char singer_t[256];
	char album_t[256];
	char mp3size_t[20];
	char * pos;
	SPEEDINFO si;
	double avgspeed;
	char avgspeed_str[10];

	if ((argc == 2 && (strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "-h") == 0))
		|| argc != 3) {
		printf("\nUsage: downmp3 keyword desfile\n\n");

		/* about information */
		printf(" +++++++++++++++++++++++++++++++\n"
			   " + Ver:    0.0.1 (10/23/2008)  +\n"
			   " + Author: Hily Jiang          +\n"
			   " + Email:  hilyjiang@gmail.com +\n"
			   " + Home:   http://hily.me/     +\n"
			   " +++++++++++++++++++++++++++++++\n");
		return 0;
	}

	/* keyword length limit: 100 bytes */
	strncpy(keyword, argv[1], 100);
	keyword[100] = 0;
	desfile = argv[2];

	/* check if the desfile is available */
	desfp = fopen(desfile, "wb");
	if (!desfp) {
		printf("Error: %s does not exists!\n", desfile);
		return -1;
	}

	/* genarate the search result page's url */
	if (gen_rsurl(keyword, rsurl) == 0) {
		printf("Error: failed to generate search result page's url!\n");
		return -1;
	}

#if DEBUG
	printf("rsurl: %s\n", rsurl);
#endif

	/* get the search result page */
	fetcher = fetcher_init();
	htmlsrc = fetcher_get(fetcher, rsurl);
	if (!htmlsrc) {
		fetcher_clean(fetcher);
		printf("Error: failed to down the page below:\n%s\n", rsurl);
		return -1;
	}
	if (find_string(htmlsrc, "<td class=d><a href=\"", "\" title", dlurl) == 0) {
		fetcher_clean(fetcher);
		printf("Sorry, can't find any song matches the keyword!\n");
		return 0;
	}
	pos = find_string(htmlsrc, "return ow(event,this)\"  target=\"_blank\">", "</a>", song_t);
	pos = find_string(pos, "<td>", "</td>", singer_t);
	pos = find_string(pos, "<td class=al>", "&nbsp;</td>", album_t);
	pos = find_string(pos, "<td> &nbsp;</td>\r\n<td>", "</td>", mp3size_t);
	fetcher_clean(fetcher);
	tidy_str(song_t, song);
	tidy_str(singer_t, singer);
	tidy_str(album_t, album);
	tidy_str(mp3size_t, mp3size);

#if DEBUG
	printf("dlurl: %s\n", dlurl);
#endif
	printf("\n");
	printf("----- Record found -----\n"
	       " + song:   %s\n"
	       " + singer: %s\n"
	       " + album:  %s\n"
	       " + size:   %s\n"
	       "-------------------------\n\n",
	       song, singer, album, mp3size);

	/* get the download page */
	fetcher = fetcher_init();
	htmlsrc = fetcher_get(fetcher, dlurl);
	if (!htmlsrc) {
		fetcher_clean(fetcher);
		printf("Error: failed to down the page below:\n%s\n", dlurl);
		return -1;
	}
	if ((find_string(htmlsrc, "disUrl(){var F=", ",L", decode_F) == 0)
	 || (find_string(htmlsrc, ";var I=\"", "\",J", decode_I) == 0)) {
		fetcher_clean(fetcher);
		printf("Error: failed to get the mp3 url!\n");
		return -1;
	}
	fetcher_clean(fetcher);

	/* decode mp3 url */
	disurl(mp3url, decode_F, decode_I);

#if DEBUG
	printf("mp3url: %s\n", mp3url);
#endif

	/* download the mp3 file */
	printf("Downloading from:\n%s\n\n", mp3url);
	if (fetcher_save(mp3url, desfp, &si)) {
		printf("\nFailed!\n");
		fclose(desfp);
		return -1;
	}
	fclose(desfp);
	if (si.lasttime == si.starttime)
		avgspeed = 0;
	else
		avgspeed = si.size/(si.lasttime-si.starttime);
	gen_speed_str(avgspeed_str, avgspeed);
	printf("\n\nAvg speed: %s\tFinished\n", avgspeed_str);

	return 0;
}

/* genarate the search result page's url */
int gen_rsurl(const char * keyword, char * rsurl)
{
	CURL *curl;
	FETCHER *fetcher;
	const char * querypage_url = "http://mp3.baidu.com/";
	const char * rsurl_1 = "http://mp3.baidu.com/m?f=ms&rn=&tn=baidump3&ct=";
	const char * rsurl_2 = "&word=";
	const char * rsurl_3 = "&lm=0";
	char *querypage_html;
	char ct[20];

	/* get the query variable ct from the query page */
	fetcher = fetcher_init();
	querypage_html = fetcher_get(fetcher, querypage_url);
	if (!querypage_html) {
		fetcher_clean(fetcher);
		return 0;
	}
	if (find_string(querypage_html, "setInput(form,\"baidump3\",\"", "\"", ct) == 0) {
		fetcher_clean(fetcher);
		return 0;
	}
	fetcher_clean(fetcher);

	/* join the string to rsurl */
	strcpy(rsurl, rsurl_1);
	strcat(rsurl, ct);
	strcat(rsurl, rsurl_2);
	curl = curl_easy_init();
	strcat(rsurl, curl_easy_escape(curl, keyword, 0));
	curl_easy_cleanup(curl);
	strcat(rsurl, rsurl_3);

	return strlen(rsurl);
}

void tidy_str(char * src, char * res)
{
	filter_tag(src);
	replace(src, "\n", "", res);
	replace(res, "&nbsp;", " ", src);
	replace(src, "&quot;", "\"", res);
	replace(res, "&lt;", "<", src);
	replace(src, "&gt;", ">", res);
	replace(res, "&amp;", "&", src);
	strcpy(res, src);
}

